<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>超市购物车实现</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      table {
        width: 500px;
        text-align: center;
      }

      tr {
        height: 30px;
        line-height: 30px;
      }

      .total {
        text-align: right;
      }
    </style>
  </head>
  <body>
    <div id="cart"></div>
    <table>
      <thead>
        <tr>
          <th>序号</th>
          <th>名字</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
        </tr>
      </thead>
      <tbody></tbody>
      <tfoot>
        <tr>
          <td class="total" colspan="5"></td>
        </tr>
      </tfoot>
    </table>
    <script>
      // const items = [
      //   {
      //     id:+new Date(),
      //     name:'红掌',
      //     price:28,
      //     quantity:2,
      //   },
      //   {
      //     id:+new Date(),
      //     name:'千里香',
      //     price:28,
      //     quantity:2,
      //   },
      //   {
      //     id:+new Date(),
      //     name:'薄荷',
      //     price:28,
      //     quantity:2,
      //   },
      //   {
      //     id:+new Date(),
      //     name:'迷迭香',
      //     price:28,
      //     quantity:2,
      //   }
      // ]
      const tbody = document.querySelector('tbody');
      // 商品构造函数用于创建购物车实例
      function ShoppingCart(){
       this.items = []
       this.totalPrice = 0
      }
      
      // 添加商品 ShoppingCart.prototype.addItem
      ShoppingCart.prototype.addItem=function(item){
        this.items.push(item)
      }
      // 删除商品
      ShoppingCart.prototype.removeItem = function(id){
        const index =  this.items.findIndex((item)=>item.id === id)
        
        this.items.splice(index,1)
        console.log(this.items); 
      }
      // 更新商品数量
      ShoppingCart.prototype.updateItem = function (id , num){
        const res = this.items.find((item)=> item.id === id)
        res.quantity = num
        console.log(this.items);
      }

      const car = new ShoppingCart()
      car.addItem({id:1,name:'红掌',price:8,quantity:2})
      car.addItem({id:2,name:'千里香',price:18,quantity:1})
      car.addItem({id:3,name:'迷迭香',price:2,quantity:4})
      console.log(car);
      car.removeItem(3)
      car.updateItem(1,4)


      function render( { items } ){
       console.log(items);
       const list = items.map((item)=>{return `
        <tr>
              <td>${item.id}</td>
              <td>${item.name}</td>
              <td>${item.price}</td>
              <td>${item.quantity}</td>
              <td>${item.price*item.quantity}</td>
        </tr>
        `})
        tbody.innerHTML = list.join('')
      }
      render(car)

    </script>
  </body>
</html>
